/*
* $Id: HideWindow.cpp 331 2011-08-12 09:28:20Z volokaleks@yandex.ru $
*
* Copyright 2009-2011 by Volokitin Aleksey
* All rights reserved
*
*/
#include "Common/include.h"
#include "HideWindow.h"
#include "Visual/SyncWizard.h"
#include "Visual/UserMessage.h"

#define ID_CLOSE	1
#define ID_SYNC		2

CHideWindow::CHideWindow(){
	m_bSyncStarted = false;
	Create(AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW), _T(""),
		0, CRect(0,0,0,0), GetDesktopWindow(), 0);
	m_niData.cbSize = NOTIFYICONDATA_V1_SIZE;
	m_niData.uID = 1;
	m_niData.uFlags = NIF_ICON|NIF_MESSAGE|NIF_TIP;
	m_niData.hIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDR_MAINFRAME));
	m_niData.uCallbackMessage = UM_TRAY_ICON;
	m_niData.hWnd = m_hWnd;
	memcpy(m_niData.szTip, _T("Apiary"), 7* sizeof(TCHAR));
	Shell_NotifyIcon(NIM_ADD,&m_niData);
}
CHideWindow::~CHideWindow(){
	Shell_NotifyIcon(NIM_DELETE,&m_niData);
	DestroyWindow();
}

BEGIN_MESSAGE_MAP(CHideWindow, CWnd)
	ON_COMMAND(ID_CLOSE, OnClose)
	ON_COMMAND(ID_SYNC, OnSync)
	ON_MESSAGE(UM_TRAY_ICON, OnTrayIcon)
END_MESSAGE_MAP()

LRESULT CHideWindow::OnTrayIcon(WPARAM wParam, LPARAM lParam){
	switch(lParam)
	{
	case WM_RBUTTONUP:
		CMenu menu;
		menu.CreatePopupMenu();
		menu.AppendMenu(MF_STRING | (m_bSyncStarted ? MF_DISABLED | MF_GRAYED : MF_ENABLED), ID_SYNC,
			ILanguageManager::GetLanguageManager()->GetString(SYNC_ID).c_str());
		menu.AppendMenu(MF_STRING, ID_CLOSE,
			ILanguageManager::GetLanguageManager()->GetString(CLOSED_ID).c_str());
		CPoint point;
		GetCursorPos(&point);
		menu.TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, point.x, point.y, this);
		break;
	}
	return TRUE;
}

void CHideWindow::OnClose(){
	PostQuitMessage(0);
}

void CHideWindow::OnSync(){
	if(!m_bSyncStarted)
	{
		m_bSyncStarted = true;
		CSyncWizard wizard;
		wizard.DoModal();
		m_bSyncStarted = false;
	}
}
